<template>
    <div class="container">
        <div id="main" class="chart"></div>
        <el-select v-model="localdata" placeholder="请选择省份" style="width: 200px;" @change="getdatabody">
            <el-option v-for="province in provinces" :key="province" :label="province" :value="province" />
        </el-select>
        <div class="sidebar">
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import { toRefs, reactive } from 'vue';
import axios from 'axios';

export default {
    setup() {
        const state = reactive({
            data: [],
            selectedProvince: '',
            localdata: '平和质',
            provinces: [],
            bodydata: [],
        })
        getdata()
        function getdata() {
            axios.get('/api/tcmsampledata/local')
                .then(function (response) {
                    // 成功处理
                    const result = response.data;
                    if (result.code === 200) {
                        state.data = result.data;
                    }
                })
                .catch(function (error) {
                    // 错误处理
                    console.log(error);
                })
                .finally(function () {
                    // 总是执行
                });
        }
        getdatabody()
        function getdatabody() {
            axios.get('/api/tcmsampledata/body', {
                params: {
                    body: state.localdata
                }
            })
                .then(function (response) {
                    // 成功处理
                    const result = response.data;
                    if (result.code === 200) {
                        state.bodydata = result.data.tcmSampleDataVOList;
                        state.provinces = result.data.locallist
                    }
                    console.log("++", state.bodydata);
                })
                .catch(function (error) {
                    // 错误处理
                    console.log(error);
                })
                .finally(function () {
                    // 总是执行
                });
        }
        return {
            ...toRefs(state),
            getdata,
            getdatabody
        }
    },


    name: 'ChinaMap',
    mounted() {
        this.initMap();
    },
    watch: {
        bodydata(newVal) {
            if (newVal && newVal.length > 0) {
                this.renderMap();
            }
        }
    },
    methods: {
        initMap() {
            fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
                .then(response => response.json())
                .then(data => {
                    echarts.registerMap('china', data);
                    this.renderMap();
                });
        },

        //中国地图
        renderMap() {
            const chartDom = document.getElementById('main');
            if (!chartDom) {
                console.error("地图容器未找到");
                return;
            }

            // 销毁旧的 ECharts 实例
            if (this.myChart) {
                this.myChart.dispose();
            }

            // 初始化新的 ECharts 实例
            this.myChart = echarts.init(chartDom);

            // 检查 state.data 是否为空
            if (!this.data || this.data.length === 0) {
                console.error("地图数据为空");
                return;
            }

            // 将 state.data 转换为 ECharts 需要的格式
            const mapData = this.data.map(item => ({
                name: item.local,
                value: item.count
            }));

            const option = {
                title: {
                    text: '人数分布图',
                    left: 'center',
                    textStyle: {
                        color: '#FFF' // 设置标题颜色为红色
                    }
                },
                tooltip: {
                    trigger: 'item',
                    showDelay: 0,
                    transitionDuration: 0.2
                },
                visualMap: {
                    left: 'right',
                    min: 0,
                    max: 800,
                    inRange: {
                        color: ['#2BDB54', '#DB2B2B', '#DBB22B', '#254AC7', '#21233A']
                    },
                    text: ['高', '低'],           // 文本，默认为数值文本
                    calculable: true
                },
                series: [
                    {
                        name: '中国省份',
                        type: 'map',
                        mapType: 'china',
                        roam: true,
                        label: {
                            show: true,
                            formatter: (params) => {
                                // 直接使用最新的 bodydata 数据
                                const target = this.bodydata.find(item => item.local === params.name);
                                return target ? `${target.count}` : '';
                            },
                            color: '#000',
                            fontSize: 12,
                            fontWeight: 'bold'
                        },
                        itemStyle: {
                            borderColor: 'rgba(0, 0, 0, 0.2)'
                        },
                        emphasis: {
                            label: {
                                show: true
                            },
                            itemStyle: {
                                areaColor: '#FFD700'
                            }
                        },
                        data: mapData
                    }
                ]
            };
            try {
                this.myChart.setOption(option);
            } catch (error) {
                console.error("地图渲染失败：", error);
            }
        },
    },

}
</script>

<style scoped>
.container {
    top: 0;
    left: 0;
    position: absolute;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    display: flex;
    width: 100%;
    height: 100vh;
}

.chart {
    width: 100vw;
    height: 100vh;
}

.pie-chart {
    width: 100%;
    height: 400px;
    margin-top: 20px;
}
</style>